<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="项目编码" prop="projectCode">
            <el-input v-model="formData.projectCode" placeholder="请输入项目编码" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="交付经理" prop="projectManagerId">
            <el-input v-model="formData.projectManagerId" placeholder="请输入交付经理" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属地市" prop="region">
            <el-input v-model="formData.region" placeholder="请输入所属地市" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="上传附件" prop="files" style="margin-bottom: 10px">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              multiple
              :limit="3"
              class="upload-demo"
              action=""
              :auto-upload="false"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
              :on-error="handleError"
              :on-exceed="handleExceed"
              accept=".pdf,.doc,.docx,.xls,.xlsx,.pptx,.ppt,.txt,.jpg,.png"
              :on-change="handleChange"
            >
              <el-button type="primary" plain>
                <Icon class="mr-5px" icon="ep:upload-filled" />
                选取文件
              </el-button>
            </el-upload>
            <div class="limitStyle"
              >最多可上传3个，小于100MB，仅支持doc、docx、xls、xlsx、ppt、pptx、pdf、txt、jpg、png类型文件</div
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as IctApi from '@/api/project/ict'
import * as KmsApi from '@/api/project/kms'
import { FormRules } from 'element-plus'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('新增案例') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  projectCode: '',
  projectName: '',
  projectManagerId: '',
  region: '',
  files: []
})
const fileList = ref([]) // 绑定的文件列表
const uploadRef = ref()
const formRules = reactive<FormRules>({
  projectCode: [{ required: true, message: '项目编码不能为空', trigger: 'blur' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  projectManagerId: [{ required: true, message: '交付经理不能为空', trigger: 'blur' }],
  region: [{ required: true, message: '所属地市不能为空', trigger: 'blur' }],
  files: [{ required: true, message: '上传附件不能为空', trigger: 'blur' }]
})

const emit = defineEmits(['success', 'getProjectInfo'])
const formRef = ref()

// 文件列表移除文件提示
const beforeRemove = (uploadFile) => {
  return ElMessageBox.confirm(`取消上传文件 ${uploadFile.name} 吗?`).then(
    () => true,
    () => false
  )
}

// 上传错误提示
const handleError = () => {
  ElMessage.error('导入文件失败，请您重新上传！')
}

// 删除上传文件
const handleRemove = (file) => {
  const index = fileList.value.map((f) => f.name).indexOf(file.name)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

//限制数量
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `您本次选择了 ${files.length} 个文件, 当前共 ${
      files.length + uploadFiles.length
    } 个文件，最多可上传1个文件`
  )
}

// 上传文件限制大小和当次不能重复
const handleChange = (uploadFile, uploadFiles) => {
  let fileSize = Number(uploadFile.size / 1024 / 1024)
  if (fileSize > 100) {
    ElMessage.warning('文件大小不能超过100MB，请您重新上传！')
    const index = fileList.value.map((f) => f.name).indexOf(uploadFile.name)
    if (index > -1) {
      fileList.value.splice(index, 1)
    }
    return
  }
  fileList.value = uploadFiles
  if (
    fileList.value.findIndex((f) => f.name === uploadFile.name) !=
    fileList.value.findLastIndex((f) => f.name === uploadFile.name)
  ) {
    ElMessage.info(uploadFile.name + ' 文件已存在!')
    fileList.value.pop()
  }
}

// 文件上传
const uploadFile = async (file) => {
  const uploadData = new FormData()
  uploadData.append('resource_name', file.name || '')
  uploadData.append('resource_id', '')
  uploadData.append('file_type', '制度库')
  uploadData.append('file', file)
  try {
    const response = await KmsApi.uploadFile(uploadData)
    return response
  } catch (error) {
    console.error('File upload error:', error)
    throw error
  }
}

// 打开弹窗
const open = async () => {
  resetForm()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const submitForm = async () => {
  // 上传所有文件
  const fileIds = []
  for (const file of fileList.value) {
    const fileId = await uploadFile(file.raw)
    fileIds.push(fileId)
  }
  formData.files = fileIds
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  ElMessageBox.confirm(`确认新增案例【${formData.projectName}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 提交请求
      formLoading.value = true
      try {
        if (dialogTitle.value === '新增案例') {
          await IctApi.createCase(formData)
          ElMessage.success('新增成功！')
          // 重置表单
          resetForm()
          fileList.value = []
          uploadRef.value.clearFiles()
        }
        dialogVisible.value = false
        //发送操作成功的事件
        emit('success', true)
      } finally {
        formLoading.value = false
      }
    })
    .catch(() => {
      ElMessage.info('已取消新增')
    })
}

// 重置表单
const resetForm = () => {
  formData.projectCode = ''
  formData.projectName = ''
  formData.projectManagerId = ''
  formData.region = ''
  formData.files = []
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
:deep(.el-upload--picture-card) {
  background: #fff;
}
.limitStyle {
  font-size: 12px;
  color: rgb(246 132 132);
  line-height: 16px;
}
</style>